import logging
import os
import yaml
from typing import Dict, Any, Tuple, List
from .base_collector import BaseCollector
from src.utils.shell_execute import remote_execute


def get_nginx_config() -> Tuple[str, str]:
    current_file_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_file_path)
    app_config_path = os.path.join(current_dir_path, "..", "..", "config", "app_config.yaml")
    try:
        with open(app_config_path, "r") as f:
            app_config = yaml.safe_load(f)
        nginx_config = app_config.get("nginx", {})
        return nginx_config.get("port", ""), nginx_config.get("status_url", "status")
    except Exception as e:
        logging.error(f"Failed to parse app_config.yaml: {e}")
        return "", ""


def parse_nginx_status_text(text: str) -> dict:
    result = {}
    try:
        lines = text.strip().splitlines()
        if len(lines) < 3:
            raise ValueError("stub_status 响应格式不正确")

        # 第一行：Active connections: 291
        active_line = lines[0]
        if "Active connections" in active_line:
            result["active_connections"] = int(active_line.split(":")[1].strip())

        # 第二行跳过
        parts = lines[2].strip().split()
        result["accepts"] = int(parts[0])
        result["handled"] = int(parts[1])
        result["requests"] = int(parts[2])

        kv_pairs = lines[3].replace(":", "").split()
        for i in range(0, len(kv_pairs), 2):
            result[kv_pairs[i].lower()] = int(kv_pairs[i + 1])
    except Exception as e:
        # 根据需求，这里可以记录日志或忽略异常
        pass
    return result


class NginxCollector(BaseCollector):
    def __init__(self, **kwargs):
        nginx_port, status_url = get_nginx_config()
        status_url = status_url.lstrip("/")
        if not nginx_port or not status_url:
            logging.warning("Nginx port or status_url is not properly set in config.")

        cmd = f"curl -s http://127.0.0.1:{nginx_port}/{status_url}"
        kwargs["cmds"] = [cmd]
        super().__init__(**kwargs)
        self.cmd = cmd

    def parse_cmd_stdout(self, nginx_info_stdout: Dict[str, Any]) -> Dict:
        raw_output = nginx_info_stdout.get(self.cmd, "")
        return parse_nginx_status_text(raw_output)

    def data_process(self, nginx_parse_result: Dict) -> Dict:
        return nginx_parse_result

